<template>
  <div class="text-container container">
    <h1 v-for="(item, index) in titleData" :key="index"
    :style="{'cursor': title.length>1?'pointer':'auto'}"
    @click="titleData.length!=1 && selectCurrent(index)"
    :class="{'current': item.current}">{{item.title}}</h1>
    <slot name="content"></slot>
    <div class="more-container" v-if="moreHrefUrl!='' && moreHref.name ">
        <a :href="moreHrefUrl">
            <p>{{moreHref.name}}</p>
            <i class="iconfont">&#xe662;</i>
        </a>
    </div>
  </div>
</template>

<script>
import { reactive, ref } from 'vue'
import { getGoodsMoreLink } from '@/api/home'

export default {
  name: 'VmGoodsText',
  props: {
    title: {
        type: Array,
        defalut: () => []
    },
    moreHref: {
        type: Object,
        defalut: reactive({
            hrefUrl: '',
            name: ''
        })
    }
  },
  setup (props, context) {
    // 将字符串转为对象
    const titleData = ref([])
    titleData.value = props.title.map(item => {
       return reactive({
            title: item,
            current: ref(false)
        })
    })
     // 添加选中状态，默认给第一个添加选中,其余不选中
    titleData.value[0].current = true

    // 链接
    const moreHrefUrl = ref(props.moreHref.hrefUrl)

    const oldCurrentTitleIndex = ref(0); // 选中的老标题索引
    const selectCurrent = index => {
        if (index==oldCurrentTitleIndex.value) return // 已经选中点击无效
        moreHrefUrl.value = getGoodsMoreLink(titleData.value[index].title) // 更新链接
        titleData.value[index].current = true // 选中新的
        titleData.value[oldCurrentTitleIndex.value].current = false // 老的取消选中
        oldCurrentTitleIndex.value = index // 更新索引
        context.emit('currentTitle', index)
    }

    return { titleData, selectCurrent, moreHrefUrl }
  }
}
</script>

<style lang="scss" scoped>
.text-container {
    display: flex;
    flex-direction: row;
    position: relative;
    align-items: center;
    h1 {
        color: #52616b;
        font-size: 18px;
        opacity: 0.6;
        margin-right: 4%;
    }
    h1.current {
        color: #1e2022;
        font-size: 24px;
        font-weight: 400;
        line-height: 32px;
        opacity: 1;
    }
    .more-container {
        position: absolute;
        right: 0;
        a {
            display: flex;
            flex-direction: row;
            align-items: center;
            color: #52616b;
            font-size: 14px;
        }  
    }
}
</style>>
